package controllers.user;



import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import services.ProjectService;
import services.RegistrationService;
import controllers.AbstractController;
import domain.Project;
import domain.Registration;
import forms.ProjectForm;

@Controller
@RequestMapping("/registration/user")
public class RegistrationUserController extends AbstractController {
	

	@Autowired
	private RegistrationService registrationService;
	@Autowired
	private ProjectService projectService;
	
	

	public RegistrationUserController() {
		super();
	}
	
	//Create
		@RequestMapping(value = "/create", method = RequestMethod.GET)
		public ModelAndView create(@RequestParam int projectId) {
			ModelAndView result;
			Collection<Project> projects;
			Project project;
			Registration registration;
			ProjectForm projectForm;
			Boolean canJoin;
			Boolean recruiting;
			
			project = projectService.findOne(projectId);
			registration = registrationService.create(project);
			registration.setProject(project);
			
			canJoin = projectService.findAvailableProjects().contains(project);
			recruiting = project.getStatus().equals("Recruiting");
			
			projectForm = projectService.projectToForm(project);
			try {
				registrationService.save(registration);
				result = new ModelAndView("project/joinedList");
				projects = projectService.findJoinedProjects();
				result.addObject("projects", projects);
			} catch (Throwable oops) {
				result = createEditModelAndView(projectForm, "project.commit.error");
				result.addObject("recruiting", recruiting);
				result.addObject("canJoin", canJoin);
				result.addObject("projectId", projectId);
			}
			
			return result;
			
		}
		
		// Ancillary methods
		protected ModelAndView createEditModelAndView(ProjectForm projectForm) {
			ModelAndView result;
			result = createEditModelAndView(projectForm, null);
			return result; 

		}

		protected ModelAndView createEditModelAndView(ProjectForm projectForm, String message) {
			ModelAndView result;
			result = new ModelAndView("project/edit");
			result.addObject("projectForm", projectForm);
			result.addObject("message", message);

			return result;

		}
		
		


}
